<!--  -->
<template>
  <div class="app-container">
    <!-- 头部搜索 -->
    <div style="width: 100%">
      <searchForm :option-list="optionList" @handle-query="handleQuery" @handle-clear="handleClear">
      </searchForm>
    </div>

    <el-button size="small" @click="consentBatch">{{
      alterSaleIdsList.length > 1 ? '批量同意' : '同意'
    }}</el-button>
    <el-button size="small" @click="rejectBatch">{{
      alterSaleIdsList.length > 1 ? '批量驳回' : '驳回'
    }}</el-button>
    <el-button size="small" icon="el-icon-download" style="margin-top: 10px" @click="exportHand">{{
      alterSaleIdsList.length ? '批量导出' : '导出数据'
    }}</el-button>
    <!-- 表格 -->
    <public-table
      :table-head="tableHead"
      :table-data="tableData"
      :show-select="showSelect"
      :show-index="showIndex"
      style="margin-top: 10px"
      @handle-selection="handleSelection"
    >
      <template slot="afterSaleStatus" slot-scope="slotProps">
        <div class="status">
          <span class="status-color" :style="{ background: slotProps.data.statusColor }"></span>
          <span>{{ slotProps.data.statusName }}</span>
        </div>
        <!-- <span>{{ slotProps.data.afterSaleStatus | afterSaleStatusFilter }}</span> -->
      </template>
      <template slot="payMethod" slot-scope="slotProps">
        <span>{{ slotProps.data.payMethod | payMethodFilter }}</span>
      </template>
      <template slot="orderSource" slot-scope="slotProps">
        <span>{{ slotProps.data.orderSource | orderSourceFilter }}</span>
      </template>
      <template slot="logisticsCompany" slot-scope="slotProps">
        <span>{{ slotProps.data.logisticsCompany | logisticsCompanyFilter }}</span>
      </template>
      <template slot="handle" slot-scope="slotProps">
        <el-button type="text" @click="goDetail(slotProps.data)"> 详情 </el-button>
        <el-button
          type="text"
          :disabled="slotProps.data.afterSaleStatus != 'WAIT_VERIFY'"
          @click="consent(slotProps.data)"
        >
          同意
        </el-button>
        <el-button
          type="text"
          :disabled="slotProps.data.afterSaleStatus != 'WAIT_VERIFY'"
          :style="{ color: slotProps.data.afterSaleStatus != 'WAIT_VERIFY' ? '#cccccc' : 'red' }"
          @click="reject(slotProps.data)"
        >
          驳回
        </el-button>
      </template>
    </public-table>
    <!-- 分页 -->
    <Pagination
      ref="myPagination"
      :sum-total="sumTotal"
      @handle-size="handlePageSize"
      @handle-current="handlePageCurrent"
    />
  </div>
</template>

<script>
import fileDownload from 'js-file-download'
import { Basic } from '@/api/base'
import { saleVerify } from '@/api/sale'
import searchForm from '@/components/Search/searchForm'
import PublicTable from '@/components/Tables/PublicTable'
import Pagination from '@/components/Pagination'
import { getToken } from '@/utils/auth'

export default {
  components: {
    searchForm,
    PublicTable,
    Pagination
  },
  filters: {
    orderTypeFilter(orderType) {
      if (orderType === 'NORMAL_ORDER') {
        return '普通订单'
      } else if (orderType === 'EXCHANGE_ORDER') {
        return '换货订单'
      } else {
        return ''
      }
    },
    orderSourceFilter(orderSource) {
      if (orderSource === 'APPLETS') {
        return '小程序'
      } else if (orderSource === 'APP') {
        return 'APP'
      } else if (orderSource === 'PC') {
        return 'PC'
      } else if (orderSource === 'H5') {
        return 'H5'
      } else {
        return ''
      }
    },
    logisticsCompanyFilter(logisticsCompany) {
      if (logisticsCompany === 'YTO_EXPRESS') {
        return '圆通快递'
      } else if (logisticsCompany === 'SF_EXPRESS') {
        return '顺丰快递'
      } else if (logisticsCompany === 'STO_EXPRESS') {
        return '申通快递'
      } else if (logisticsCompany === 'ZTO_EXPRESS') {
        return '中通快递'
      } else if (logisticsCompany === 'YUN_DA_EXPRESS') {
        return '韵达快递'
      } else if (logisticsCompany === 'EMS') {
        return '邮政快递'
      } else {
        return ''
      }
    },
    afterSaleStatusFilter(afterSaleStatus) {
      if (afterSaleStatus === 'WAIT_VERIFY') {
        return '待审核'
      } else if (afterSaleStatus === 'WAIT_SHIP') {
        return '待换货'
      } else if (afterSaleStatus === 'EXCHANGED') {
        return '已发货'
      } else if (afterSaleStatus === 'FINISHED') {
        return '已完成'
      } else if (afterSaleStatus === 'REJECT') {
        return '已驳回'
      } else {
        return ''
      }
    },
    payMethodFilter(payMethod) {
      if (payMethod === 'ALIPAY') {
        return '支付宝'
      } else if (payMethod === 'WECHAT') {
        return '微信'
      } else {
        return ''
      }
    }
  },
  data() {
    return {
      showSelect: true, // 表格多选
      showIndex: false, // 表格序号
      searchData: {},
      alterSaleIds: [], // 换货单号
      alterSaleIdsList: [], // 批量换货单号
      type: true, // 同意&驳回
      // 订单状态
      optionsStatus: [
        { value: 'WAIT_VERIFY', label: '待审核', color: '#FAAD14' },
        { value: 'WAIT_SHIP', label: '待换货', color: '#FF4D4F' },
        { value: 'EXCHANGED', label: '已发货', color: '#1890FF' },
        { value: 'FINISHED', label: '已完成', color: '#52C41A' },
        { value: 'REJECT', label: '已驳回', color: '#cccccc' }
      ],
      // 搜索
      optionList: [
        {
          label: '',
          type: 'input',
          placeholder: '用户账号',
          key: 'account',
          width: '120'
        },
        {
          label: '',
          type: 'input',
          placeholder: '换货单号',
          key: 'afterSaleId',
          width: '120'
        },
        {
          label: '',
          type: 'input',
          placeholder: '原订单号',
          key: 'orderId',
          width: '120'
        },
        {
          label: '',
          type: 'select',
          placeholder: '订单状态',
          key: 'afterSaleStatus',
          width: '120',
          list: [
            { value: 'WAIT_VERIFY', label: '待审核' },
            { value: 'WAIT_SHIP', label: '待换货' },
            { value: 'EXCHANGED', label: '已发货' },
            { value: 'FINISHED', label: '已完成' },
            { value: 'REJECT', label: '已驳回' }
          ]
        }
      ],
      // 表头
      tableHead: [
        { label: '换货单号', value: 'afterSaleId' },
        { label: '订单金额', value: 'totalMoney' },
        { label: '处理状态', type: 'slot', slotName: 'afterSaleStatus' },
        { label: '支付方式', type: 'slot', slotName: 'payMethod' },
        { label: '订单来源', type: 'slot', slotName: 'orderSource' },
        { label: '用户账号', value: 'account' },
        { label: '申请换货时间', value: 'createTime', width: 180 },
        { label: '运费', value: 'expressCharge' },
        { label: '同意换货时间', value: 'agreeTime', width: 180 },
        { label: '付款金额', value: 'payMoney' },
        { label: '运单号', value: 'waybillNumber' },
        { label: '物流公司', type: 'slot', slotName: 'logisticsCompany' },
        { label: '原订单号', value: 'orderId' },
        { label: '操作', type: 'slot', slotName: 'handle', width: 150 }
      ],
      // 表格数据
      tableData: [],
      // 分页配置
      sumTotal: 0,
      currentPage: 1,
      pageSize: 10
    }
  },
  mounted() {
    this.getTableData()
  },
  methods: {
    // 数据列表
    getTableData() {
      const vm = this
      const params = JSON.parse(JSON.stringify(vm.searchData))
      params.pageNum = vm.currentPage
      params.pageSize = vm.pageSize
      Basic.list('order/after_sale', params).then(res => {
        if (res.code === 200) {
          const { data } = res
          const arr = data.records
          vm.tableData = arr.map(i => {
            const { afterSaleStatus } = i
            const activeItem = vm.optionsStatus.filter(i => i.value === afterSaleStatus)
            if (activeItem.length) {
              i.statusColor = activeItem[0].color
              i.statusName = activeItem[0].label
            }
            return i
          })
          // vm.tableData = data.records
          // console.log('tableData', vm.tableData)
          vm.sumTotal = data.total
        }
      })
    },
    // 分页
    handlePageSize(val) {
      this.pageSize = val
      this.getTableData()
    },
    handlePageCurrent(val) {
      this.currentPage = val
      this.getTableData()
    },
    // 查询
    handleQuery(e) {
      // console.log('查询：', e)
      const that = this
      that.searchData = Object.assign(e)
      that.currentPage = 1
      that.$refs.myPagination.currentPage = 1
      that.getTableData()
    },
    // 重置
    handleClear() {
      const that = this
      that.searchData = {}
      that.currentPage = 1
      that.$refs.myPagination.currentPage = 1
      that.getTableData()
    },
    // 多选
    handleSelection(e) {
      const that = this
      if (e && e.length > 0) {
        that.alterSaleIdsList = e.map(item => item.afterSaleId)
        // console.log('多选：', that.alterSaleIdsList)
      } else {
        that.alterSaleIdsList = []
      }
    },
    // 同意
    consent(e) {
      const that = this
      this.$confirm('此操作将同意换货请求, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          that.alterSaleIds = [e.afterSaleId]
          that.type = true
          // console.log('同意：', that.alterSaleIds)
          that.audit()
          that.alterSaleIds = []
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作',
            center: true,
            duration: 500
          })
          that.alterSaleIds = []
        })
    },
    // 驳回
    reject(e) {
      this.$confirm('此操作将驳回换货请求, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const that = this
          that.alterSaleIds = [e.afterSaleId]
          that.type = false
          // console.log('驳回：', that.alterSaleIds)
          that.audit()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作',
            center: true,
            duration: 500
          })
        })
    },
    // 批量同意
    async consentBatch() {
      const that = this
      if (that.alterSaleIdsList.length > 0) {
        const alterSaleIdsList = JSON.parse(JSON.stringify(that.alterSaleIdsList))
        that.type = false
        const params = {
          alterSaleIds: alterSaleIdsList,
          type: true
        }
        saleVerify(params).then(res => {
          if (res.code === 200) {
            that.getTableData()
            this.$message({
              type: 'success',
              message: '操作成功!',
              center: true,
              duration: 500
            })
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: '请选择订单!',
          center: true,
          duration: 500
        })
      }
    },
    // 批量驳回
    rejectBatch() {
      const that = this
      if (that.alterSaleIdsList.length > 0) {
        const alterSaleIdsList = JSON.parse(JSON.stringify(that.alterSaleIdsList))
        that.type = false
        const params = {
          alterSaleIds: alterSaleIdsList,
          type: false
        }
        saleVerify(params).then(res => {
          if (res.code === 200) {
            that.getTableData()
            this.$message({
              type: 'success',
              message: '操作成功!',
              center: true,
              duration: 500
            })
          }
        })
      } else {
        this.$message({
          type: 'error',
          message: '请选择订单!',
          center: true,
          duration: 500
        })
      }
    },
    // 审核方法
    audit() {
      const that = this
      const params = {
        alterSaleIds: that.alterSaleIds,
        type: that.type
      }
      // console.log('params:', params)
      saleVerify(params).then(res => {
        if (res.code === 200) {
          that.getTableData()
          this.$message({
            type: 'success',
            message: '操作成功!',
            duration: 500
          })
        }
      })
    },
    // 导出
    exportHand() {
      const that = this
      const idList = JSON.parse(JSON.stringify(that.alterSaleIdsList))
      const url = idList.length ? 'export' : 'export/all'
      const params = idList.length ? { alterSaleId: idList } : {}
      that.$axios
        .get(`${process.env.VUE_APP_BASE_API}/order/after_sale/${url}`, {
          responseType: 'blob',
          headers: {
            Authorization: getToken()
          },
          params
        })
        .then(res => {
          fileDownload(res.data, '换货数据.xlsx')
        })
        .catch(err => {
          const { response } = err
          if (response.status && response.status === 401) {
            that.$message.error('暂无操作权限，请联系管理员！')
          }
        })
    },
    // 跳转详情
    goDetail() {
      this.$router.push({
        path: 'sales-detail'
        // query: {
        //   orderId: orderId
        // }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.status {
  .status-color {
    float: left;
    width: 8px;
    height: 8px;
    margin: 6px;
    border: none;
    border-radius: 10px;
  }
}
</style>
